/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.wwl.linkedqueue;

import com.wwl.arrayqueue.Queue;

/**
 * @author Neil Wang
 * @version 1.0.0
 * @date 2021/6/10 3:36 下午
 */
@SuppressWarnings("all")
public class LinkedListQueue<T> implements Queue<T> {

    private Node<T> head, tail;
    private int size;

    public LinkedListQueue() {
    }

    @Override
    public void enqueue(T t) {
        if (tail == null) {
            tail = new Node<>(t);
            head = tail;
        } else {
            tail.setNext(new Node(t));
            tail = tail.next();
        }
        size++;
    }

    @Override
    public T dequeue() {
        if (isEmpty()) throw new IllegalStateException("Cannot dequeue from an empty queue");
        Node<T> ret = head;
        head = head.next();
        ret.setNext(null);
        if (head == null) tail = null;
        size--;
        return ret.data();
    }

    @Override
    public T getFront() {
        if (isEmpty()) throw new IllegalStateException("Queue is empty");
        return head.data();
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        res.append("Queue : FRONT->");
            for (Node cur = head; cur != null; cur = cur.next()) res.append(cur + "->");
            res.append("TAIL");
        return res.toString();
    }

}
